package com.situ.mall.service.impl;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.mall.common.ServerResponse;
import com.situ.mall.dao.CategoryMapper;
import com.situ.mall.entity.Category;
import com.situ.mall.entity.CategoryCount;
import com.situ.mall.service.ICategoryService;
import com.situ.mall.util.JedisPoolUtil;

import redis.clients.jedis.Jedis;

@Service
public class CategoryServiceImpl implements ICategoryService{

	@Autowired
	private CategoryMapper categoryMapper;
	
	@Override
	public ServerResponse selectTopCategory() {
		List<Category> list = categoryMapper.selectTopCategory();
		return ServerResponse.createSuccess("", list);
	}

	@Override
	public ServerResponse selectSecondCategory(Integer topCategoryId) {
		List<Category> list = categoryMapper.selectSecondCategory(topCategoryId);
		return ServerResponse.createSuccess("", list);
	}

	@Override
	public ServerResponse getCategoryProductCount() {
		List<CategoryCount> list = categoryMapper.getCategoryProductCount();
		return ServerResponse.createSuccess("", list);
	}

	@Override
	public List<Category> selectTopCategoryList() {
		// 获取jedis客户端
		Jedis jedis = JedisPoolUtil.getJedis();
		if (jedis != null) {
			String topCategoryListJson = jedis.get("topCategoryList");
			ObjectMapper objectMapper = new ObjectMapper();
			if (null == topCategoryListJson || topCategoryListJson.length() == 0) {
				System.out.println("redis中没有数据，查询数据库");
				List<Category> topCategoryList = categoryMapper.selectTopCategory();
				try {
					String jsonData = objectMapper.writeValueAsString(topCategoryList);
					jedis.set("topCategoryList", jsonData);
				} catch (JsonProcessingException e) {
					e.printStackTrace();
				}
				return topCategoryList;
			} else {
				System.out.println("redis中有，查询缓存");
				List<Category> list = null;
				try {
					list = objectMapper.readValue(topCategoryListJson,new TypeReference<List<Category>>() { });
				} catch (IOException e) {
					e.printStackTrace();
				}
				return list;
			}
		} else {
			System.out.println("无法获取Jedis");
			return categoryMapper.selectTopCategory();
		}
	}

	@Override
	public List<Category> selectSecondCategoryList() {
		return categoryMapper.selectSecondCategoryList();
	}
	

}
